package com.recruit.mail;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.mail.HtmlEmail;

import com.eos.data.datacontext.IMapContextFactory;
import com.eos.data.datacontext.IRequestMap;
import com.eos.system.annotation.Bizlet;
import com.recruit.talent.sublabel;
@Bizlet("")
/**
 * @param content 邮件正文
 * @param theme 主题
 * @param fileUrl 附件
 * @param toMail 收件人
 * @param ccMail 抄送人
 * @param host 邮箱服务器
 * @param protococ 邮件发送协议 
 * @param port 邮件服务器默认端口
 * @param userMail 用户邮箱
 * @param loginName 登录名
 * @param password 密码
 * @param IsMultiple 是否群发
 * @param position 待入职人员职位
 * @return state 返回值
 */
public class Email {
	private EmailParam param ;
	
	@Bizlet("发送邮件")
	public  String sentMailToTxt(String content,String theme,String fileUrl,String toMail,String nickName,String ccMail,
		String bccMail,String host,String protococ,String port,String userMail,
		String loginName,String password,boolean IsMultiple,String position,String url) throws Exception{
		//返回值
		String state="";
		if(param==null){
			param = new EmailParam();
			param.setHost(host);
			param.setProtococ(protococ);
			param.setPort(port);
			param.setUserMail(userMail);
			param.setLoginName(loginName);
			param.setPassword(password);
		}
		
		//IsMultiple 为true 为群发
		if(IsMultiple==true){
			//收件人邮箱
			String[] recipient = toMail.split(",");
			//收件人邮箱
			String[] URL=null;
			if(url!="" && url!=null && url!="null"){
				
				URL = url.split(",");
			}
			
			
				for(int i = 0 ; i <recipient.length;i++){
					int k = recipient[i].indexOf("<");
					String subName = "";
					if( k == -1){
						subName = recipient[i];
					}else{
						subName= recipient[i].substring(0, recipient[i].indexOf("<"));
					}
					//替换群发邮件正文的待入职人员的姓名
					String  repContent  = content.replaceAll("\\{[ 姓名 ^}]*\\}", subName);
					if(url!="" && url!=null && url!="null"){
						//替换群发邮件正文的待入职人员的姓名
						repContent  = repContent.replaceAll("\\{[ 链接 ^}]*\\}", URL[i]);
					}
					
					//待入职人员职位字符串转换为数组
					if(position!=null){
						
					
					String[] positions =position.split(",") ;
					repContent = repContent.replaceAll("\\{[ 职位 ^}]*\\}", positions[i]);
					}
					try{
					sendMail(param,fileUrl,recipient[i],nickName,ccMail,bccMail,theme,repContent);
					}catch(AuthenticationFailedException e){
						state="工号或密码错误";
					}catch (MessagingException e) {
						state="发送错误";
					}
			  }
			
		}else{
					try{
						String repContent=content;
					if(url!="" && url!=null && url!="null"){
						
						url=url.substring(0,url.length()-1);
						//替换群发邮件正文的待入职人员的姓名
						repContent  = content.replaceAll("\\{[ 链接 ^}]*\\}", url);
					}
					sendMail(param,fileUrl,toMail,nickName,ccMail,bccMail,theme,repContent);
					}catch(AuthenticationFailedException e){
						state="工号或密码错误";
					}catch (MessagingException e) {
						state="发送错误";
					}
			
		}
		return state;
	}
	
	public static void sendMail(EmailParam param,String fileUrl,String recipient,String nickName,String ccMail,String bccMail,String theme,String content)throws Exception{
		
				//系统属性
				Properties prop = new Properties();
		        prop.setProperty("mail.smtp.host", param.getHost());
		        prop.setProperty("mail.transport.protocolz", param.getProtococ());
		        prop.setProperty("mail.smtp.port", param.getPort());
		        prop.setProperty("mail.smtp.auth", "true");

		        //创建session
		        Session session = Session.getInstance(prop);
		       
		        //通过session得到transport对象
		        Transport ts = session.getTransport(param.getProtococ());
		        //使用邮箱的用户名和密码连上邮件服务器，发送邮件时，发件人需要提交邮箱的用户名和密码给smtp服务器，用户名和密码都通过验证之后才能够正常发送邮件给收件人。
		        ts.connect(param.getHost(), param.getLoginName(),param.getPassword());
		        
		      //邮件主题
				String title = theme;
				
				String[] filesUrl={};
				//判断附件不能为空
				if(fileUrl != null || fileUrl == ""){
					//创建一个对象，引用一个对象的字符串转数组方法
					sublabel sub = new sublabel();
					filesUrl= sub.stringTurnArray(fileUrl)	;
				}
				//定义一个字符串数组来存储收件人
				String[] recipientMail = {};
				if(recipient!=null){
					recipientMail = new String[]{recipient};
				}
				//定义一个字符串数组来存储密送人
				String[] bccMails = {};
				if(bccMail!=null){
					bccMails = new String[] {bccMail};
				}
				
				//判断抄送人不能为kong
				if(ccMail!=null){
					ccMail+=","+param.getUserMail();
				}else{
					ccMail=param.getUserMail();
				}
				//定义一个字符串数组来存储抄送人
				String[] ccMails = {ccMail};
				
		
		        //创建邮件
		        Message message = createSimpleMail(session,recipientMail,nickName,ccMails,bccMails,content.toString(),title,param.getUserMail(),filesUrl);
		        //发送邮件
		        ts.sendMessage(message,message.getAllRecipients());
		        ts.close();
	}
	
	 public static MimeMessage createSimpleMail(Session session,String[] recipient,String nickName,String[] ccMail ,String[] bccMail, String content,String title,String userMail,String[] filesUrl)
	            throws Exception {
	    	
	 
	        //创建邮件对象
	        MimeMessage message = new MimeMessage(session);
	        String nick=""; 
	    	//指明邮件的发件人
	        InternetAddress to;
	        if(nickName!="" && nickName!=null && nickName!="null"){
	        	nick=javax.mail.internet.MimeUtility.encodeText(nickName);
	        	//指明邮件的发件人
		        to=new InternetAddress(nick+"<"+userMail+">");
	        }else{
	        	//指明邮件的发件人
	        	to=new InternetAddress(userMail);
	        }
	        message.setFrom(to);
	     
	        //收件人
	        String recipients = "";
	        if(recipient.length>0){
	        	 recipients=getMailList(recipient);
	        	 message.setRecipients(Message.RecipientType.TO, recipients);
	        }
	        
	        
	        //密送人
	        String bccMails = "";
	        if(bccMail.length>0){
	        	bccMails = getMailList(bccMail);
	        	message.setRecipients(Message.RecipientType.BCC, bccMails);
	        }
	        
	        
	        //抄送人
	        String ccMails = "";
	        if(ccMail.length>0){
	        	ccMails = getMailList(ccMail);
			    message.setRecipients(Message.RecipientType.CC,ccMails);
	        }
	       
	        
	       
	        //指明邮件的收件人，现在发件人和收件人是一样的，那就是自己给自己发
	        //邮件的标题
	        message.setSubject(title);
	        message.setSentDate(new Date());
	        
	        // 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件  
	        Multipart multipart = new MimeMultipart();  
	        //添加邮件正文  
	        BodyPart contentBodyPart = new MimeBodyPart();
	     
	        //邮件内容  
	        contentBodyPart.setContent(content, "text/html;charset=UTF-8");  
	        multipart.addBodyPart(contentBodyPart);
	        
	       
	        // 添加附件  
	        String filesPath = "";
	        //附件长度大于0
	        if(filesUrl.length>0){
	        		
	        //获取文件目录路劲
	        IMapContextFactory contextFactory = com.primeton.ext.common.muo.MUODataContextHelper.getMapContextFactory();
		    IRequestMap requestMap = contextFactory.getRequestMap();
		    HttpServletRequest  request = (HttpServletRequest) requestMap.getRootObject();
		    String rootpath =request.getSession().getServletContext().getRealPath("");
		        	
	        for(int i = 0;i<filesUrl.length;i++){
	        	//文件目录拼接附件
	        	filesPath = rootpath+"/"+filesUrl[i];
	        	//附件不能等于空
	        	 if (filesPath != null && !"".equals(filesPath)) {  
	        		 	//添加附加内容
	        		    BodyPart attachmentBodyPart = new MimeBodyPart();  
	        		    // 根据附件路径获取文件,  
	        		    FileDataSource dataSource = new FileDataSource(filesPath);  
	        		    attachmentBodyPart.setDataHandler(new DataHandler(dataSource));  
	        		    //MimeUtility.encodeWord可以避免文件名乱码  
	        		    attachmentBodyPart.setFileName(MimeUtility.encodeWord(dataSource.getFile().getName()));  
	        		    multipart.addBodyPart(attachmentBodyPart);  
	        		            
	        		   }  
	        		}	        		
	        	}
	    
	        // 邮件的文本内容  
	        message.setContent(multipart);  
	        
	        //返回创建好的邮件对象
	        return message;
	    }
	 	
	 //对多个收件人进行处理
	 public static String getMailList(String[] receipt){
		 
		 StringBuffer sb = new StringBuffer();
		 
		 if(receipt!=null && receipt.length<2){
			 if(receipt[0].contains("@")){
					sb.append(receipt[0]); 
				} 
			  return sb.toString().substring(0,sb.toString().length());
		 }else{
			 
			 for(int i =0;i<receipt.length;i++){
				 if(receipt[0].contains("@")){
					 sb.append(receipt[i]+",");
				 }
			 }
			 return sb.toString().substring(0,sb.toString().length()-1);
		 }
	 }
	 
}
